package com.feiyue.learning.distributionlock;

import org.I0Itec.zkclient.IZkDataListener;

import java.util.concurrent.CountDownLatch;

/**
 * 同名非时序节点分布式锁
 * @author  feiyue
 * @date  2020/5/3
 */
public class ZkDistributionLock1 extends ZkAbstractLock {

    private CountDownLatch countDownLatch = null;

    @Override
    public boolean tryLock() {
        try {
            zkClient.createEphemeral(LOCK_1);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    public void waitLock() {
        IZkDataListener listener = new IZkDataListener() {
            @Override
            public void handleDataChange(String dataPath, Object data) throws Exception {

            }

            @Override
            public void handleDataDeleted(String dataPath) throws Exception {
                if (countDownLatch != null) {
                    countDownLatch.countDown();
                }
            }
        };
        zkClient.subscribeDataChanges(LOCK_1, listener);

        if (zkClient.exists(LOCK_1)) {
            countDownLatch = new CountDownLatch(1);
            try {
                countDownLatch.await();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 取消监听
        zkClient.unsubscribeDataChanges(LOCK_1, listener);
    }

    @Override
    public void unlock() {
        if (zkClient != null) {
            zkClient.delete(LOCK_1);
            zkClient.close();
        }
    }
}
